//
//  HMOAuthViewController.swift
//  Weibo-walker
//
//  Created by 郭彬 on 16/3/5.
//  Copyright © 2016年 guobin. All rights reserved.
//

import UIKit

class HMOAuthViewController: UIViewController {

    
    
    // APPKEY
    let WB_CLIENT_ID = "685474061"
    // 回调页
    let WB_REDIRECT_URI = "http://www.sharma.cn/"
    /// SECRET
    let WB_CLIENT_SECRET = "00baf350dea7d32250f47916cf8c6b52"
    
    override func viewDidLoad() {
        super.viewDidLoad()
                
        setupUI()
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WB_CLIENT_ID)&redirect_uri=\(WB_REDIRECT_URI)")
        
        let request = NSURLRequest.init(URL:url!)
        
        webView.loadRequest(request)
        
        let url2 = request.URL!
        
        print(url2.query)

        
        
        
    }

    
    
    //MARK: - 懒加载 webView
    lazy var webView: UIWebView = {
    
        let  webView = UIWebView()

        webView.delegate = self
        return webView
    }()
    func setupUI(){
        
        navigationItem.title = "新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancel")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFill")
    }
    
    override func loadView() {
        
        view = webView
        
    }
    
    @objc private func cancel(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    /// 自动填充


    @objc private func autofill() {
        
        print("autofill")
//        let JSString = "document.getElementById('userId').value = 'bin5211bin@163.com';document.getElementById('passwd').value = '7083963**'"
//        webView.stringByEvaluatingJavaScriptFromString(JSString)
   
    }

}
extension HMOAuthViewController:UIWebViewDelegate{
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let url  = request.URL else {
            return false
        }
        // 判断地址的字符串是否是以回调页开头
        if !url.absoluteString.hasPrefix(WB_REDIRECT_URI) {
            return true
        }
        let  query = url.query!
        print(query)
        if !query.hasPrefix("code=") {
            let code = query.substringToIndex("aaaaa".endIndex)
            print("获取回来的code是:\(code)")
            return true
        }
        let code = query.substringToIndex("aaaaa".endIndex)
        print("回来的code是:\(code)")
        return false
        
    }
}
